package com.wlyuan.open.scanner.repository.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.wlyuan.open.OpenBaseSyncDTO;
import com.wlyuan.open.constants.CarrierTypeEnum;
import com.wlyuan.open.scanner.application.factory.SyncFactory;
import com.wlyuan.open.scanner.config.ScannerProperties;
import com.wlyuan.open.scanner.constant.Constants;
import com.wlyuan.open.scanner.dao.entity.BalanceCheckDetailsDO;
import com.wlyuan.open.scanner.dao.entity.BasicAreaDO;
import com.wlyuan.open.scanner.dao.entity.OrderIndexDO;
import com.wlyuan.open.scanner.dao.mapper.OrderIndexMapper;
import com.wlyuan.open.scanner.dao.mapper.SupplierMapper;
import com.wlyuan.open.scanner.domain.order.*;
import com.wlyuan.open.scanner.domain.transport.TransportAttach;
import com.wlyuan.open.scanner.domain.transport.TransportConvert;
import com.wlyuan.open.scanner.repository.*;
import com.wlyuan.open.scanner.utils.DateUtils;
import com.wlyuan.open.scanner.utils.NumberUtils;
import com.wlyuan.open.scanner.utils.StrUtils;
import com.wlyuan.open.scanner.utils.enums.YesOrNoEnum;
import com.wlyuan.open.scanner.utils.enums.bill.PayTypeEnum;
import com.wlyuan.open.scanner.utils.enums.order.AttachTypeEnum;
import com.wlyuan.open.scanner.utils.enums.order.OrderSignTypeEnum;
import com.wlyuan.open.scanner.utils.enums.order.OrderSrcClassEnum;
import com.wlyuan.open.scanner.utils.enums.order.OrderStatusEnum;
import com.wlyuan.open.scanner.utils.enums.tenant.ShareCompanyTypeEnum;
import com.wlyuan.open.scanner.utils.enums.transport.*;
import com.wlyuan.open.utils.LongUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class BaseOrderRepository {
    private final BasicAreaRepository basicAreaRepository;
    private final AttachRepository attachRepository;
    private final OrderGoodsRepository orderGoodsRepository;
    private final OrderAdditionTransportRepository orderAdditionTransportRepository;
    private final OrderFlowRepository orderFlowRepository;
    private final OrderSignLogRepository orderSignLogRepository;
    private final CarrierRepository carrierRepository;
    private final SyncFactory syncFactory;
    private final DriverRepository driverRepository;
    private final UserRepository userRepository;
    private final PayRepository payRepository;
    private final SupplierMapper supplierMapper;
    private final OrderIndexMapper orderIndexMapper;
    private final ScannerProperties scannerProperties;

    /**
     * 获取订单附件
     *
     * @param orderId
     * @param signType
     * @return
     */
    public List<OrderAttach> attach(Long orderId, Integer signType) {
        var list = attachRepository.getByOrderId(orderId);
        //扫描签收时，签收照片类型为扫码签收(新系统分为签收照片 和 扫码签收照片)
        if (OrderSignTypeEnum.isScanSign(signType) && !CollectionUtils.isEmpty(list)) {
            list.stream().filter(x -> StringUtils.isNotBlank(x.getName())).filter(x -> AttachTypeEnum.SIGN.getValue().equals(x.getType())).forEach(t -> t.setType(AttachTypeEnum.SCANNER_SIGN.getValue()));
        }
        //同步过来的回单照片处理
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().filter(x -> StringUtils.isNotBlank(x.getName())).filter(x -> AttachTypeEnum.RECEIPT.getValue().equals(x.getType()) && YesOrNoEnum.isYes(x.getSyncThisTag())).forEach(t -> t.setType(AttachTypeEnum.RECEIPT_SYNC.getValue()));
        }

        return OrderConvert.convertAttach(list);
    }

    public List<TransportAttach> attach(Long orderId) {
        var list = attachRepository.getByOrderId(orderId);
        return TransportConvert.convertAttach(list);
    }

    /**
     * 订单物品
     *
     * @param orderId
     * @return
     */
    public List<OrderGoods> getOrderGoodsByOrderId(Long orderId, Long tenantId) {
        return orderGoodsRepository.getByOrderId(orderId, tenantId);
    }

    /**
     * 获取订单运输信息
     *
     * @param orderId
     * @return
     */
    public List<OrderTransport> getOrderAdditionTransport(Long orderId, boolean isAdditionTransportType) {
        //如果有补充轨迹信息，则返回轨迹信息
        if (isAdditionTransportType) {
            return orderAdditionTransportRepository.getByOrderId(orderId);
        }
        return Collections.emptyList();
    }

    /**
     * 地址
     *
     * @param data
     */
    public void processAddress(OrderIndexDO data) {
        if (StringUtils.isNotBlank(data.getIndexDescription()) && data.getIndexDescription().length() > Constants.REMARK_LENGTH) {
            data.setIndexDescription(data.getIndexDescription().substring(0, Constants.REMARK_LENGTH));
        }
        if (StringUtils.isBlank(data.getIndexEndusername())) {
            data.setIndexEndusername(data.getIndexToman());
        }
        if (StringUtils.isBlank(data.getFromProvinceName())) {
            Optional.ofNullable(basicAreaRepository.getArea(data.getIndexFromprovince())).ifPresent(fromProvince -> data.setFromProvinceName(fromProvince.getAreaName()));
        }
        if (StringUtils.isBlank(data.getFromCityName())) {
            Optional.ofNullable(basicAreaRepository.getArea(data.getIndexFromcity())).ifPresent(fromCity -> data.setFromCityName(fromCity.getAreaName()));
        }
        if (StringUtils.isBlank(data.getFromDistrictName())) {
            Optional.ofNullable(basicAreaRepository.getArea(data.getIndexFromdistrict())).ifPresent(fromDistrict -> data.setFromDistrictName(fromDistrict.getAreaName()));
        }
        if (StringUtils.isBlank(data.getToProvinceName())) {
            Optional.ofNullable(basicAreaRepository.getArea(data.getIndexToprovince())).ifPresent(toProvince -> data.setToProvinceName(toProvince.getAreaName()));
        }
        if (StringUtils.isBlank(data.getToCityName())) {
            Optional.ofNullable(basicAreaRepository.getArea(data.getIndexTocity())).ifPresent(toCity -> data.setToCityName(toCity.getAreaName()));
        }
        if (StringUtils.isBlank(data.getToDistrictName())) {
            Optional.ofNullable(basicAreaRepository.getArea(data.getIndexTodistrict())).ifPresent(toDistrict -> data.setToDistrictName(toDistrict.getAreaName()));
        }
    }

    /**
     * 补差
     *
     * @param data
     */
    public void valueAddition(OrderIndexDO data) {
        data.setIndexTotalvolume(NumberUtils.sub(data.getIndexTotalvolume(), data.getIndexVolumeaddition()));
        data.setIndexTotalweight(NumberUtils.sub(data.getIndexTotalweight(), data.getIndexWeightaddition()));
    }

    /**
     * 地区信息
     *
     * @param order
     * @return
     */
    private Map<Long, BasicAreaDO> getAreaIds(OrderIndexDO order) {
        List<Long> list = new ArrayList<>(6);
        list.add(order.getIndexFromprovince());
        list.add(order.getIndexToprovince());
        list.add(order.getIndexFromcity());
        list.add(order.getIndexTocity());
        list.add(order.getIndexFromdistrict());
        list.add(order.getIndexTodistrict());
        list = list.stream().filter(LongUtils::notNullLong).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyMap();
        }
        return basicAreaRepository.getAreaMap(list);
    }

    /**
     * 承运商
     *
     * @param order
     */
    public void processCarrier(OrderIndexDO order) {
        if (order.getIndexSrcclass() == null || OrderSrcClassEnum.CLIENT_ORDER.getValue().equals(order.getIndexSrcclass())) {
            return;
        }
        //线上承运方
        onlineSupplier(order);
        //线下承运方
        offlineSupplier(order);
        //自营司机承运方
        driverSupplier(order);
    }

    public void processCarrier(OrderIndexDO order, Long upTenantId) {
        if (LongUtils.notNullLong(upTenantId) && LongUtils.notNullLong(order.getIndexCreatorcompanyid())) {
            var supplier = carrierRepository.getOnlineByCompanyId(upTenantId, order.getIndexCreatorcompanyid());
            Optional.ofNullable(supplier).ifPresent(down -> {
                order.setCarrierId(down.getId());
                order.setCarrierName(down.getName());
                order.setCarrierContactName(down.getContactName());
                order.setCarrierPhone(down.getContactMobile());
                order.setCarrierType(CarrierTypeEnum.ONLINE.getValue());
                order.setUpTenantId(down.getTenantId());
            });
        }
    }

    /**
     * 线上承运方
     */
    private void onlineSupplier(OrderIndexDO order) {
        if (LongUtils.notNullLong(order.getIndexSupplierid())) {
            //线上承运商
            var supplier = carrierRepository.getOnlineById(order.getIndexSupplierid());
            Optional.ofNullable(supplier).ifPresent(down -> {
                order.setCarrierId(order.getIndexSupplierid());
                order.setCarrierName(down.getName());
                order.setCarrierContactName(down.getContactName());
                order.setCarrierPhone(down.getContactMobile());
                order.setCarrierType(CarrierTypeEnum.ONLINE.getValue());
                order.setUpTenantId(down.getTenantId());
            });

        }
    }

    /**
     * 线下承运方
     */
    private void offlineSupplier(OrderIndexDO order) {
        if (LongUtils.notNullLong(order.getIndexSuppliersymbolid())) {
            //线下
            var symbol = carrierRepository.getOfflineById(order.getIndexSuppliersymbolid());
            Optional.ofNullable(symbol).ifPresent(s -> {
                order.setCarrierType(CarrierTypeEnum.OFFLINE.getValue());
                order.setCarrierId(order.getIndexSuppliersymbolid());
                order.setCarrierName(s.getName());
                order.setCarrierContactName(s.getContactName());
                order.setCarrierPhone(s.getContactMobile());
                order.setUpTenantId(s.getTenantId());
            });
        }
    }

    /**
     * 自营司机承运方
     */
    private void driverSupplier(OrderIndexDO order) {
        if (LongUtils.notNullLong(order.getIndexDriverid())) {
            //自营司机
            var driver = driverRepository.getById(order.getIndexDriverid());
            Optional.ofNullable(driver).ifPresent(d -> {
                order.setCarrierType(CarrierTypeEnum.DRIVER.getValue());
                order.setUpTenantId(d.getTenantId());
            });
        }
    }

    /**
     * 场景证书
     */
    public void cert(OrderIndexDO data) {
        data.setGenerateCert(orderSignLogRepository.getCertByOrder(data.getIndexId(), data.getIndexRootorderid(), data.getIndexSrcclass()));
    }

    /**
     * 调度
     */
    public void dispatch(OrderIndexDO data) {
        var orderFlow = orderFlowRepository.getDispatchFlowByOrderId(data.getIndexId());
        Optional.ofNullable(orderFlow).ifPresent(flow -> {
            data.setDispatchBy(flow.getFlowCreator());
            data.setDispatchAt(flow.getFlowInserttime());
        });
    }

    /**
     * 签收
     */
    public void sign(OrderIndexDO data, boolean isWayBill) {
        var signInfo = signInfo(data);
        Optional.ofNullable(signInfo).ifPresent(sign -> {
            data.setIndexSigntime(sign.getIndexSigntime());
            data.setSignTenant(sign.getSignTenant());
            data.setSignDesc(sign.getSignDesc());
            data.setSignCreateTime(sign.getSignCreateTime());
            data.setSignFlowId(sign.getSignFlowId());
            data.setIndexSinger(sign.getIndexSinger());
            data.setIndexStatus(sign.getIndexStatus());
        });

        //类型是扫码签收，并且签收时间为空时,取订单的签收信息,物品签收信息取原始订单的签收信息
        if (isWayBill && OrderSignTypeEnum.SCAN_SIGN.getValue().equals(data.getSignType()) && !data.isSign() && !data.getIndexId().equals(data.getIndexRootorderid())) {
            Optional.ofNullable(orderIndexMapper.getById(data.getIndexRootorderid())).ifPresent(root -> {
                var rootSignInfo = signInfo(root);
                Optional.ofNullable(rootSignInfo).ifPresent(rootSign -> {
                    data.setIndexSigntime(rootSign.getIndexSigntime());
                    data.setSignTenant(rootSign.getSignTenant());
                    data.setSignDesc(rootSign.getSignDesc());
                    data.setSignCreateTime(rootSign.getSignCreateTime());
                    data.setSignFlowId(rootSign.getSignFlowId());
                    data.setIndexSinger(rootSign.getIndexSinger());
                    data.setIndexStatus(rootSign.getIndexStatus());

                    //物品签收信息
                    if (!CollectionUtils.isEmpty(data.getGoodsList())) {
                        var rootGoodsList = getOrderGoodsByOrderId(root.getIndexId(), root.getIndexCreatorcompanyid());
                        if (!CollectionUtils.isEmpty(rootGoodsList)) {
                            data.getGoodsList().forEach(d -> {
                                var orderGoods = rootGoodsList.stream().filter(x -> d.getGoodsId().equals(x.getGoodsId())).findAny().orElse(null);
                                Optional.ofNullable(orderGoods).ifPresent(goods -> {
                                    d.setGoodsSign(goods.getGoodsSign());
                                });
                            });
                        }
                    }

                });
            });
        }
        //签收人为99 时，老系统为自动签收，用户不存在，为0
        if (data.getIndexSinger() != null && Constants.AUTO_SIGNER.equals(data.getIndexSinger())) {
            data.setIndexSinger(0L);
        }
    }

    private OrderSingInfo signInfo(OrderIndexDO data) {
        OrderSingInfo singInfo = new OrderSingInfo();
        singInfo.setIndexSigntime(data.getIndexSigntime());
        singInfo.setIndexSinger(data.getIndexSinger());
        singInfo.setIndexStatus(data.getIndexStatus());
        //状态为待调度,待签收,已关闭,签收时间为空或者1900,签收人为0，则签收人设置为null
        if (OrderStatusEnum.isSignerZero(data.getIndexStatus()) && !data.isSign() && !LongUtils.notNullLong(data.getIndexSinger())) {
            data.setIndexSinger(null);
        }

        if (OrderStatusEnum.isWaitReceipt(data.getIndexStatus()) && data.getIndexVerifysigintime() != null && !Constants.YEAR.equals(data.getIndexVerifysigintime().getYear())) {
            singInfo.setIndexSigntime(data.getIndexVerifysigintime());
        }
        if (LongUtils.notNullLong(data.getIndexSinger())) {
            var user = userRepository.getUserTenant(data.getIndexSinger());
            Optional.ofNullable(user).ifPresent(u -> singInfo.setSignTenant(u));
        }

        var orderFlow = orderFlowRepository.getSignFlowByOrderId(data.getIndexId());
        Optional.ofNullable(orderFlow).ifPresent(flow -> {
            singInfo.setSignDesc(flow.getFlowDescription());
            singInfo.setSignCreateTime(flow.getFlowInserttime());
            singInfo.setSignTenant(flow.getFlowCompanyid());
            singInfo.setSignFlowId(flow.getFlowId());
            if (!LongUtils.notNullLong(data.getIndexSinger()) && LongUtils.notNullLong(flow.getFlowCreator())) {
                singInfo.setIndexSinger(flow.getFlowCreator());
            }
            if (DateUtils.dateTimeDefaultToNull(singInfo.getIndexSigntime()) == null) {
                singInfo.setIndexSigntime(flow.getFlowInserttime());
            }
            if (singInfo.getIndexStatus() != null && singInfo.getIndexStatus().compareTo(OrderStatusEnum.WAIT_RECEIPT.getValue()) < 0) {
                singInfo.setIndexStatus(OrderStatusEnum.WAIT_RECEIPT.getValue());
            }
        });
        return singInfo;
    }

    /**
     * 回单
     */
    public void receipt(OrderIndexDO data, boolean signToReceipt) {
        //状态为已回单，回单时间为空，并且签收时间不为空，取签收时间
        if (OrderStatusEnum.DONE.getValue().equals(data.getIndexStatus()) && !data.isReceipt() && data.isSign()) {
            data.setIndexReceiptime(data.getIndexSigntime());
            data.setReceiptBy(data.getIndexSinger());
        }
        var orderFlow = orderFlowRepository.getReceiptFlowByOrderId(data.getIndexId());
        Optional.ofNullable(orderFlow).ifPresent(flow -> {
            data.setReceiptBy(flow.getFlowCreator());
            data.setReceiptCreateTime(flow.getFlowInserttime());
            data.setReceiptDesc(flow.getFlowDescription());
            data.setReceiptTenant(flow.getFlowCompanyid());
            data.setReceiptFlowId(flow.getFlowId());
            if (DateUtils.dateTimeDefaultToNull(data.getIndexReceiptime()) == null) {
                data.setIndexReceiptime(flow.getFlowInserttime());
            }
            if (data.getIndexStatus() != null && data.getIndexStatus().compareTo(OrderStatusEnum.DONE.getValue()) < 0) {
                data.setIndexStatus(OrderStatusEnum.DONE.getValue());
            }
        });
        //已回单,并且回单时间为空时,可能是个体司机，老系统个体司机的回单和签收是一样的
        if (signToReceipt && OrderStatusEnum.DONE.getValue().equals(data.getIndexStatus()) && data.getIndexReceiptime() == null && LongUtils.notNullLong(data.getIndexSupplierid())) {
            var supplier = supplierMapper.getById(data.getIndexSupplierid());
            Optional.ofNullable(supplier).ifPresent(s -> {
                //是否个体司机
                if (ShareCompanyTypeEnum.isPersonal(s.getPersonal())) {
                    data.setSignToReceipt(true);
                    data.setReceiptType(TransportReceiptTypeEnum.NORMAL.getValue());
                    data.setReceiptLabel(TransportReceiptLabelEnum.NORMAL.getValue());
                    data.setIndexReceiptime(data.getIndexSigntime());
                    data.setReceiptBy(data.getIndexSinger());
                    data.setReceiptCreateTime(data.getSignCreateTime());
                    data.setReceiptDesc(data.getSignDesc());
                    data.setReceiptTenant(data.getSignTenant());
                }
            });
        }
    }

    /**
     * 关单
     */
    public void close(OrderIndexDO data) {
        if (StringUtils.isBlank(data.getIndexFromman())) {
            data.setIndexFromman(data.getCustomerName());
        }
        if (StringUtils.isBlank(data.getIndexToman())) {
            data.setIndexToman(data.getIndexEndusername());
        }
        //承运方客户单关闭的时候，状态直接变为待调度，这里拿不到关闭原因和关闭信息,flow表中也会产生两条一样的数据（除了描述内容不一样）
        //已关闭 或者 发起关单
        if (data.isClose() || TransportCloseStatusEnum.closeIng(data.getCloseStatus())) {
            var orderFlow = data.isClose() ? orderFlowRepository.getCloseFlowByOrderId(data.getIndexId()) : orderFlowRepository.getCloseIngFlowByOrderId(data.getIndexId(), data.getIndexClosemark());
            Optional.ofNullable(orderFlow).ifPresent(flow -> {
                data.setCloseAt(flow.getFlowInserttime());
                data.setCloseBy(flow.getFlowCreator());
                data.setCloseTenant(flow.getFlowCompanyid());
                data.setCloseFlowId(flow.getFlowId());
                if (OrderSrcClassEnum.isOrder(data.getIndexSrcclass())) {
                    data.setCloseReason(data.getIndexClosement());
                } else {
                    data.setCloseReason(StrUtils.closeReason(flow.getFlowDescription()));
                }
            });
            //运输单
            if (OrderSrcClassEnum.isTransport(data.getIndexSrcclass()) && (TransportCloseStatusEnum.OPERATION_START.getValue().equals(data.getIndexClosemark()) || TransportCloseStatusEnum.OPERATION_CLOSED.getValue().equals(data.getIndexClosemark()))) {
                if (TransportCloseStatusEnum.OPERATION_START.getValue().equals(data.getIndexClosemark())) {
                    data.setCloseToTenantId(data.getIndexSuppliercompanyid());
                }
                if (TransportCloseStatusEnum.OPERATION_CLOSED.getValue().equals(data.getIndexClosemark())) {
                    data.setCloseToTenantId(data.getIndexCreatorcompanyid());
                }
            }
            //拼车单
            if (OrderSrcClassEnum.isCombine(data.getIndexSrcclass()) && (TransportCloseStatusEnum.SERVICE_CLOSE_NOTIFY.getValue().equals(data.getIndexClosemark()) || TransportCloseStatusEnum.SERVICE_CLOSED.getValue().equals(data.getIndexClosemark()))) {
                if (TransportCloseStatusEnum.SERVICE_CLOSED.getValue().equals(data.getIndexClosemark())) {
                    if (LongUtils.notNullLong(data.getIndexSuppliercompanyid())) {
                        data.setCloseToTenantId(data.getIndexSuppliercompanyid());
                    } else {
                        data.setCloseToTenantId(data.getIndexCreatorcompanyid());
                    }
                }
            }
        }
        //拒绝
        var orderFlow = orderFlowRepository.getRefuseReasonByOrderId(data.getIndexId());
        Optional.ofNullable(orderFlow).ifPresent(flow -> {
            //关单同意后,会生成一条 订单状态变为待调度 的操作记录，与 操作了拒绝后的数据一样，故在取拒绝原因时，判断下内容是否包含 拒绝原因字样
            if (StringUtils.isNotBlank(flow.getFlowDescription()) && flow.getFlowDescription().contains("拒绝原因")) {
                data.setRefuseAt(flow.getFlowInserttime());
                data.setRefuseBy(flow.getFlowCreator());
                data.setRefuseTenant(flow.getFlowCompanyid());
                data.setRefuseFlowId(flow.getFlowId());
                data.setRefuseReason(StrUtils.refuseReason(flow.getFlowDescription()));
            }
        });
    }

    /**
     * 运单回单类型转换成新系统回单类型和回单标记
     *
     * @param data
     */
    public void transportReceipt(OrderIndexDO data, boolean signToReceipt) {
        //老系统 null （没回单） 0 (没回单，正常回单) 1 补单 2 丢单  3 正常回单
        //新系统 回单类型：receipt_type 0 (正常回单)  1 补单  丢失标记：receipt_label 0（没回单，正常回单） 1 回单丢失
        var type = data.getIndexReceipttype();
        //没回单或者正常回单
        if (ReceiptTypeEnum.isInit(type) || ReceiptTypeEnum.isNormal(type)) {
            data.setReceiptLabel(TransportReceiptLabelEnum.NORMAL.getValue());
            data.setReceiptType(null);
            //有回单时间时，则为已回单
        }
        if (data.isReceipt()) {
            data.setReceiptType(TransportReceiptTypeEnum.NORMAL.getValue());
        }
        //补单
        if (ReceiptTypeEnum.isReplenish(type)) {
            data.setReceiptType(TransportReceiptTypeEnum.REPLENISH.getValue());
            data.setReceiptLabel(TransportReceiptLabelEnum.NORMAL.getValue());
        }
        //丢单
        if (ReceiptTypeEnum.isLost(type)) {
            data.setReceiptType(null);
            data.setReceiptLabel(TransportReceiptLabelEnum.LOST.getValue());
        }
        //回单操作信息
        receipt(data, signToReceipt);
    }

    public void financeFlag(OrderIndexDO data, Long downId) {
        var list = new ArrayList<>(Arrays.asList(data.getIndexId()));
        Map<Long, Long> orderTypeMap = new HashMap<>(5);
        orderTypeMap.put(data.getIndexId(), data.getIndexSrcclass());
        if (LongUtils.notNullLong(downId)) {
            list.add(downId);
            orderTypeMap.put(downId, OrderSrcClassEnum.CLIENT_ORDER.getValue());
        }
        var result = payRepository.getByOrderIdAndType(list, null);
        if (!CollectionUtils.isEmpty(result)) {
            var map = result.stream().collect(Collectors.groupingBy(BalanceCheckDetailsDO::getCheckDetailsertype));
            map.forEach((k, v) -> {
                if (PayTypeEnum.ADVANCE.getValue().equals(k)) {
                    data.setPrepayFeeFlag(flag(orderTypeMap, v));
                }
                if (PayTypeEnum.COD.getValue().equals(k)) {
                    data.setArrivePayFeeFlag(flag(orderTypeMap, v));
                }
                if (PayTypeEnum.PAYSUB.getValue().equals(k)) {
                    data.setCollectionFeeFlag(flag(orderTypeMap, v));
                }
            });

        }
    }

    private Integer flag(Map<Long, Long> orderTypeMap, List<BalanceCheckDetailsDO> list) {
        var orderIdList = list.stream().map(BalanceCheckDetailsDO::getCheckDetailorderid).distinct().collect(Collectors.toList());
        if (orderIdList.size() > 1) {
            //已收已付
            return TransportFinanceFlagEnum.INCOMNE_PAID.getValue();
        } else {
            var orderId = orderIdList.stream().findAny().get();
            //客户单 已收
            if (OrderSrcClassEnum.isOrder(orderTypeMap.get(orderId))) {
                return TransportFinanceFlagEnum.INCOMNE.getValue();
            }
            //运输单 已付
            if (OrderSrcClassEnum.isTransport(orderTypeMap.get(orderId))) {
                return TransportFinanceFlagEnum.PAID.getValue();
            }
        }
        return null;
    }

    public void sync(OpenBaseSyncDTO source) {
        syncFactory.sync(source);
    }

    public void syncRef(OpenBaseSyncDTO source) {
        syncFactory.syncRef(source);
    }

    public boolean checkTenant(Long tenantId) {
        return StringUtils.isNotBlank(scannerProperties.getTenant()) &&
                Arrays.asList(scannerProperties.getTenant().split(",")).contains(String.valueOf(tenantId));
    }
}
